<?php

namespace addons\third\library;

use EasyWeChat\Factory;
use fast\Http;
use think\Config;
use think\Db;
use think\Session;

/**
 * 微信小程序
 */
class WechatMiniApp
{

    /**
     * 配置信息
     * @var array
     */
    private $config = [];

    public function __construct($options = [])
    {
        if ($config = Config::get('third.wechatMiniApp')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
        $config = [
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/log/'.date("Y-m-d").'/wechat.log',
            ],
        ];;
        $this->config = array_merge($this->config, $config);
    }


    /**
     * 获取小程序用户openid
     * @param array $params
     * @return array
     */
    public function getUserInfo($params = [])
    {
        $app = Factory::miniProgram($this->config);
        $res = $app->auth->session($params['code']); // session_key // openid
//        $decryptedData = $app->encryptor->decryptData($res["session_key"], $params['iv'], $params['encryptedData']);
//
//        $access_token = isset($decryptedData['access_token']) ? $decryptedData['access_token'] : '';
//        $refresh_token = isset($data['refresh_token']) ? $data['refresh_token'] : '';
//        $expires_in = isset($data['expires_in']) ? $data['expires_in'] : 0;
//
//        $res["nickname"] = $decryptedData['nickName']?:"";
//        $res['avatar'] = $decryptedData['avatarUrl']?:"";
//        $res['access_token'] = $access_token;
//        $res['refresh_token'] = $refresh_token;
//        $res['expires_in'] = $expires_in;

        return  $res;

    }

    public function getminiAppGetPhone($params){
        $app = Factory::miniProgram($this->config);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串


        if (!$params["code"]) {
            return [];
        }
        $queryarr = array(
            "code"       => $params["code"],
        );

        $headers = ['Content-type: application/json'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];
        $url= "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token["access_token"];

        $response = Http::post($url, json_encode($queryarr),$options);
        $ret = (array)json_decode($response, true);

        if($ret["errcode"] != 0){
            exception("获取手机号错误,{$ret['errmsg']}");
        }

//        $decryptedData = $app->encryptor->decryptData($res["session_key"], $params['iv'], $params['encryptedData']);

        return $ret;
    }




    public function getAppCode($path, $parma=[], $posterId, $user_id){
        $app = Factory::miniProgram($this->config);
        $response = $app->app_code->get($path,$parma);

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $fileDir = "./uploads/activity/".$posterId."/".$user_id;
            if(!is_dir($fileDir)){
                mkdir($fileDir, 0777, true);
            }
            $filename = $response->save($fileDir,$user_id.".png");
            return $fileDir."/".$filename;
        }
    }
}
